package com.itsc.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import com.itsc.entities.Repair;
import com.itsc.util.page.Page;

public class RepairDao extends BaseDao<Repair> {

	@SuppressWarnings("unchecked")
	public List<Repair> getAllRepairsByRepairState(String flag) {
		String repair_state = flag;
		String hql = "from Repair where repair_state = ?";
		Query query = getSession().createQuery(hql);
		query.setString(0, repair_state);
		List<Repair> waitingRepairList = new ArrayList<Repair>();
		waitingRepairList = query.list();
		return waitingRepairList;
	}

	@SuppressWarnings("unchecked")
	public List<Repair> getPagesByRepairState(String flag, Page page) {
		String repair_state = flag;
		String hql = "from Repair where repair_state = ?";
		Query query = getSession().createQuery(hql);
		query.setString(0, repair_state);
		if (page != null) {
			query.setFirstResult(page.getBeginIndex());
			query.setMaxResults(page.getPageSize());
		}
		List<Repair> waitingRepairList = new ArrayList<Repair>();
		waitingRepairList = query.list();
		return waitingRepairList;
	}

	public Repair selectByUserName(String user_name) {
		Repair repair = null;
		String hql = "from Repair where user_name = ?";
		Query query = getSession().createQuery(hql);
		query.setString(0, user_name);
		repair = (Repair) query.uniqueResult();
		return repair;
	}

	public Repair selectByUserPhone(String user_phone) {
		Repair repair = null;
		String hql = "from Repair where user_phone = ?";
		Query query = getSession().createQuery(hql);
		query.setString(0, user_phone);
		repair = (Repair) query.uniqueResult();
		return repair;
	}

	public int getCountByRepairState(String repair_sate) {
		String hql = "from Repair where repair_state = ?";
		Query query = getSession().createQuery(hql);
		query.setString(0, repair_sate);
		return query.list().size();
		/*
		 * int count = 0; List<Repair> repairList = new ArrayList<Repair>();
		 * repairList = getAllRepairsByRepairState(repair_sate); if(repairList
		 * != null) count = repairList.size(); return count;
		 */
	}

	@SuppressWarnings("unchecked")
	public List<Repair> search(String flag, String searchname, String datemin,
			String datemax, Page page) {
		searchname = searchname == null ? "" : searchname;
		datemin = datemin == null ? "" : datemin;
		datemax = datemax == null ? "" : datemax;
		String hql = "from Repair where repair_state = ? and (repair_person_name like ? or repair_addr like ? (go_time between ? and ?))";
		Query query = getSession().createQuery(hql);
		query.setString(0, searchname);
		query.setString(1, "%" + searchname + "%");
		query.setString(2, "%" + searchname + "%");
		query.setString(3, datemin);
		query.setString(4, datemax);
		if (page != null) {
			query.setFirstResult(page.getBeginIndex());
			query.setMaxResults(page.getPageSize());
		}
		return query.list();
	}
}
